package com.huatai.bpmn.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.huatai.bpmn.entity.TbRiskEntity;
import com.huatai.bpmn.service.TbRiskService;
import com.huatai.bpmn.mapper.TbRiskMapper;
import com.huatai.common.api.R;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 *
 */
@Service
public class TbRiskServiceImpl extends ServiceImpl<TbRiskMapper, TbRiskEntity> implements TbRiskService{


	/**
	 * 添加或更新风控表
	 * @param tbRiskEntity
	 * @return
	 */
	@Override
	public R addOrUpdateRisk(TbRiskEntity tbRiskEntity) {
		TbRiskEntity riskEntity = this.getOne(new LambdaQueryWrapper<TbRiskEntity>()
			.eq(TbRiskEntity::getRiskType, tbRiskEntity.getRiskType()));
		if (riskEntity!=null){
			return R.fail("该风险类型已存在，请勿重复添加或修改!");
		}
		return this.saveOrUpdate(tbRiskEntity)?R.data("更新成功！"):R.fail("更新失败！");
	}

	/**
	 * 获取风险清册
	 * @param jsonObject
	 * @return
	 */
	@Override
	public R findRiskList(JSONObject jsonObject) {
		Integer page = jsonObject.getInteger("page");
		Integer limit = jsonObject.getInteger("limit");
		Page<TbRiskEntity> page1 = new Page<>(page, limit);
		this.page(page1,null);
		return R.data(page1);
	}

	/**
	 * 风控监测
	 * @param jsonObject
	 * @return
	 */
	@Override
	public R riskCheck(JSONObject jsonObject) {
		try {
			String riskType = jsonObject.getString("riskType");
			TbRiskEntity riskEntity = this.getOne(new LambdaQueryWrapper<TbRiskEntity>()
				.eq(TbRiskEntity::getRiskType, riskType));
			JSONObject params = jsonObject.getJSONObject("sqlParams");
			Set<String> keySet = params.keySet();
			String querySql = riskEntity.getQuerySql();
			for (String key : keySet) {
				querySql=querySql.replace("${"+key+"}",params.getString(key));
			}
			//逆向校验，如果sql查询有结果就不通过,没有结果则通过校验
			long checkResult = SqlRunner.db().selectCount(querySql, null);
			boolean result = checkResult == 1;
			if (result){
				return R.data(false,riskEntity.getMsg());
			}else {
				return R.data(true,"校验通过");
			}
		}catch (Exception e){
			throw new RuntimeException("风控接口异常:"+e.getMessage());
		}
	}
}




